package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
@Api(tags = "Token登录")
@RestController
@RequestMapping("/sys/token")
public class TokenLoginController {

    @Autowired
    private CommonAPI commonAPI;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private  SysBaseApiImpl sysBaseApi;

    @ApiOperation(value = "Token验证", notes = "验证当前的Token是否有效")
    @GetMapping(value = "/tokenLogin")
    public Result<JSONObject> tokenLogin(HttpServletRequest request){
        Result<JSONObject> result = new Result<JSONObject>();
        // 获取请求里的token
        String token = TokenUtils.getTokenByRequest(request);
        // //转换成base64串
        //        String base64 = Base64.getEncoder().encodeToString(bytes).trim();

        // 校验token
        Boolean tokenIsUse = TokenUtils.verifyToken(token, commonAPI, redisUtil);
        JSONObject obj = new JSONObject();
        // 校验成功，返回新的token
        if(tokenIsUse) {
            return result.success("授权码有效,登录成功");
        } else {
            return result.error500("会员码已经失效,请重新授权");
        }
    }

    @ApiOperation(value = "Token置换", notes = "用当前有效的Token换取新的Token")
    @GetMapping(value = "/tokenRefresh")
    public Result<JSONObject> tokenRefresh(String paramsToken,HttpServletRequest request) {
        Result<JSONObject> result = new Result<JSONObject>();
        if (paramsToken == null || paramsToken.isEmpty()) {
            return result.error500("授权码为空，请填写授权码");
        }
        // 获取请求里的token
//        String oldToken = TokenUtils.getTokenByRequest(request);
        String t = Base64.getEncoder().encodeToString(paramsToken.getBytes()).trim();
        // 校验token
        Boolean tokenIsUse = TokenUtils.verifyToken(paramsToken, commonAPI, redisUtil);
        JSONObject obj = new JSONObject();
        // 校验成功，返回新的token
        if(tokenIsUse) {
            // 解密获得username，用于和数据库进行对比
            String username = JwtUtil.getUsername(paramsToken);
            // 拿到用户信息
            SysUser user = sysUserService.getUserByName(username);
            String password = user.getPassword();
//            String userId = user.getId();
            // 生成token
            String nextToken = JwtUtil.sign(username, password);
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + nextToken, nextToken);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + nextToken, JwtUtil.EXPIRE_TIME * 2 / 1000 * 24 * 60);
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + paramsToken);

            // 保存用户走一个service 保证事务
            user.setNextToken(nextToken);

            List roles = sysBaseApi.getRoleIdsByUsername(username);
            String role = String.valueOf("");
            for (int i = 0; i < roles.size(); i++) {
                if(i < roles.size() - 1) {
                    role = role + roles.get(i) + ',';
                } else {
                    role = role + roles.get(i);
                }
            }
            sysUserService.editUser(user, role, null);
            obj.put("newToken",nextToken);
            result.setResult(obj);
            return result.success("已完成新授权码刷新置换");
        } else {
            return result.error500("授权码已经失效,请重新授权");
        }
    }

}
